package com.jinrustar.httpfileserver.springboot.config.interceptor;


import com.jinrustar.httpfileserver.core.util.WebUtil;
import com.jinrustar.httpfileserver.springboot.annatation.LoginRequired;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    protected final static org.slf4j.Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        logger.debug("## 登录。。。");
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
        if (loginRequired != null) {
            Map requestParams = WebUtil.getParameterMap(httpServletRequest);
            String url = httpServletRequest.getRequestURL().toString();
            logger.info("登录拦截: method: {}, class: {},url:{}, params:{},ip:{}", method.getName(), method.getDeclaringClass().getSimpleName(), url, requestParams, WebUtil.getHost(httpServletRequest));
            logger.debug("## loginRequired{}", loginRequired.name());
            if (httpServletRequest.getSession().getAttribute("account") == null) {
                logger.debug("## 未登录");
                httpServletResponse.setHeader("Content-Type", "text/html;charset=utf8");
                httpServletResponse.getWriter().write("未登录");
                return false;
            }
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
